package com.ruoyi.web.controller.wps.controller;


import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.publish.domain.wps.WFileT;
import com.ruoyi.publish.domain.wps.WFileVersionT;
import com.ruoyi.publish.service.IApprovalRecordService;
import com.ruoyi.publish.service.IWFileTService;
import com.ruoyi.publish.service.IWFileVersionTService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.wps.base.Response;
import com.ruoyi.web.controller.wps.dto.FileDTO;
import com.ruoyi.web.controller.wps.dto.FileHisDTO;
import com.ruoyi.web.controller.wps.dto.FileReqDTO;
import com.ruoyi.web.controller.wps.dto.UserDTO;
import com.ruoyi.web.controller.wps.model.FileModel;
import com.ruoyi.web.controller.wps.model.UserModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
public class WebOfficeController {

    protected final Logger logger = LoggerFactory.getLogger(WebOfficeController.class);

    @Autowired
    private IWFileTService iwFileTService;
    @Value("${ruoyi.wordPath}")
    private  String  wordBaseDirtory;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWFileVersionTService iwFileVersionTService;

    @Value("${wps.download_host}")
    String download_host;

    @Value("${ruoyi.intrServerIp}")
    private  String  intrServerIp;

    //// TODO: 参数传递最好不要出现中文等特殊字符，容易导致签名不过等问题，本例子用fileid与文件名做了一个映射，实际开发可以按情况处理
    private static Map<String, String> fileNameMap = new HashMap<String, String>();

    static {
        fileNameMap.put("1", "中文.doc");
        fileNameMap.put("2", "2.xls");
        fileNameMap.put("3", "3.ppt");
    }

    @RequestMapping(value="/v1/3rd/file/info", method = RequestMethod.GET)
    @ResponseBody
    public Object fileInfo(@RequestParam("_w_fileid") String fileid,@RequestParam("_w_userid") String userid, HttpServletRequest request, HttpServletResponse response,@RequestHeader HttpHeaders headers) throws UnsupportedEncodingException {
        System.out.println("进入/v1/3rd/file/info");

        JSONObject jsonObject = new JSONObject();
        JSONObject file = new JSONObject();
        JSONObject user = new JSONObject();


//        Enumeration hears=request.getHeaderNames();
//        while(hears.hasMoreElements()) {
//            String a=(String) hears.nextElement();
//            System.out.println("header参数名="+a+"参数值="+request.getHeader(a));
//
//        }
//
//        Enumeration reqs=request.getParameterNames();
//        while(reqs.hasMoreElements()) {
//            String a=(String) reqs.nextElement();
//            System.out.println("request参数名="+a+"参数值="+request.getParameter(a));
//
//        }

        String token=  request.getHeader("x-wps-weboffice-token");
        System.out.println("from request:" + request.getHeader("x-wps-weboffice-token"));
        FileModel fileModel = new FileModel();

        WFileT wFileT=iwFileTService.selectWFileTById(Long.parseLong(fileid));
        fileModel.name=wFileT.getName();


        try {
            SysUser sysUser=null;
            if (StringUtils.isNotEmpty(userid)){
                 sysUser=userService.selectUserById(Long.parseLong(userid));

            }
            File localFile = new File(wordBaseDirtory+"/"+wFileT.getFileUrl());

            fileModel.size = localFile.length();
            //// TODO: 文件的id应该唯一
            file.put("id", fileid);
            file.put("name", fileModel.name);
            //// TODO: 文件的版本控制
            file.put("version", wFileT.getVersion());
            //// TODO: 必须返回文件真实大小，服务端会检查
            file.put("size", fileModel.size);
            file.put("creator", wFileT.getCreator());
            file.put("modifier", wFileT.getModifier());
            //// TODO: 下载链接中的参数如带中文等特殊字符，参数必须进行urlencode
            file.put("download_url", fileModel.download_url + fileid);
            jsonObject.put("file", file);
            UserModel userModel = new UserModel();
            user.put("id", userid);
            user.put("name", StringUtils.isNotEmpty(userid)?sysUser.getUserName():userModel.name);
            user.put("permission", "write");
            user.put("avatar_url", GetAvatarSet(sysUser.getUserId()));
            jsonObject.put("user", user);




        } catch (JSONException e) {
            e.printStackTrace();
        }

        System.out.println("返回数据"+jsonObject.toString());
        return jsonObject.toString();
    }

    @RequestMapping(value="/v1/3rd/file/version/{version}", method = RequestMethod.GET)
    @ResponseBody
    public Object fileVersionInfo(@PathVariable("version") Long version, @RequestParam("_w_fileid") String fileid,@RequestParam("_w_userid") String userid, HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("进入/v1/3rd/file/version/{version} version=11"+version);

        JSONObject jsonObject = new JSONObject();
        JSONObject file = new JSONObject();
        JSONObject user = new JSONObject();



        String token=  request.getHeader("x-wps-weboffice-token");
        System.out.println("from request:" + request.getHeader("x-wps-weboffice-token"));

        FileDTO fileModel = new FileDTO();
        WFileT wFileT=iwFileTService.selectWFileTById(Long.parseLong(fileid));

        WFileVersionT versionT=new WFileVersionT();
        versionT.setFileId(String.valueOf(fileid));
        versionT.setVersion(version);
        List<WFileVersionT>   versionTS=iwFileVersionTService.selectWFileVersionTList(versionT);

        if (versionTS!=null&&versionTS.size()!=0){
            WFileVersionT   ver=versionTS.get(0);
            SysUser sysUser=null;
            if (StringUtils.isNotEmpty(userid)){
                sysUser=userService.selectUserById(Long.parseLong(userid));

            }


            File localFile = new File(wordBaseDirtory+"/"+wFileT.getFileUrl());
            fileModel.setSize(localFile.length());
            fileModel.setId(ver.getFileId());
            fileModel.setName(ver.getName());
            fileModel.setVersion(ver.getVersion());
            fileModel.setSize(ver.getSize());
            fileModel.setCreator(ver.getCreator());
            fileModel.setModifier(ver.getModifier());
            fileModel.setDownload_url(download_host + "/weboffice/getHistoryFile?_w_hisfileid="+ver.getId());
//                //// TODO: 文件的id应该唯一
//                file.put("id", ver.getFileId());
//                file.put("name", ver.getName());
//                //// TODO: 文件的版本控制
//                file.put("version", version);
//                //// TODO: 必须返回文件真实大小，服务端会检查
//                file.put("size", ver.getSize());
//                file.put("creator", ver.getCreator());
//                file.put("modifier", ver.getModifier());
//                //// TODO: 下载链接中的参数如带中文等特殊字符，参数必须进行urlencode
//                file.put("download_url", download_host + "/weboffice/getHistoryFile?_w_hisfileid="+ver.getId());
//                jsonObject.put("file", file);
//                UserModel userModel = new UserModel();
//                user.put("id", userid);
//                user.put("name", StringUtils.isNotEmpty(userid)?sysUser.getUserName():userModel.name);
//                user.put("permission", "write");
//                user.put("avatar_url",  GetAvatarSet(sysUser.getUserId()));
//                jsonObject.put("user", user);


        }else{
            return jsonObject.toString();
        }


        Map<String, Object> map = new HashMap<>();
        map.put("file", fileModel);
        return map;
//        return jsonObject.toString();
    }


    @RequestMapping(value="/v1/3rd/user/info", method = RequestMethod.POST)
    @ResponseBody
    public Object userInfo(@RequestParam("_w_userid") String userid,HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入====/v1/3rd/user/info 接口");

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject user = new JSONObject();
        UserModel userModel = new UserModel();


        Enumeration reqs=request.getParameterNames();
        while(reqs.hasMoreElements()) {
            String a=(String) reqs.nextElement();
            System.out.println("request参数名="+a+"参数值="+request.getParameter(a));

        }
//        String token=  request.getHeader("x-wps-weboffice-token");
        if (StringUtils.isEmpty(userid)){
            System.out.println("_w_userid 为空");

            return jsonObject.toString();
        }
        SysUser sysUser=null;
        if (StringUtils.isNotEmpty(userid)){
            sysUser=userService.selectUserById(Long.parseLong(userid));

        }        System.out.println("from request:" + request.getHeader("x-wps-weboffice-token"));
        try {
            user.put("id", userid);
            user.put("name", StringUtils.isNotEmpty(userid)?sysUser.getUserName():userModel.name);
            user.put("permission", userModel.permission);
            user.put("avatar_url", GetAvatarSet(sysUser.getUserId()));
            jsonArray.put(user);
            jsonObject.put("users", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        System.out.println("user输出="+ JSON.toJSONString(jsonArray));

        return jsonObject.toString();
    }

    @RequestMapping(value="/v1/3rd/file/online", method = RequestMethod.POST)
    @ResponseBody
    public void online() {
    }

    @RequestMapping(value = "/v1/3rd/file/save", method = RequestMethod.POST)
    @ResponseBody
    public Object save(@RequestParam("file") MultipartFile file, @RequestParam("_w_fileid") String fileid,@RequestParam("_w_userid") String userid, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入====//v1/3rd/file/save");
        logger.info("进入====//v1/3rd/file/save");
        logger.info("_w_fileid=="+fileid);
        WFileT wFileT=iwFileTService.selectWFileTById(Long.parseLong(fileid));
        String uuid = UUID.randomUUID().toString().replaceAll("-","");

        String fileUrl="/"+wFileT.getFileUrl().split("/")[1]+"/"+uuid+".docx";
        System.out.println("fileUrl=="+fileUrl);
        String newFileName=wordBaseDirtory+fileUrl;
        System.out.println("newFileName=="+newFileName);
        logger.info("newFileName="+newFileName);
        long   newSize=0L;
        if (!file.isEmpty()) {
            try {
                logger.info("fileNotNull---newFileName="+newFileName);
                File saveFile=new File(newFileName);

                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                newSize=saveFile.length();
                System.out.println("新保存文件=="+newSize+"  信息=="+saveFile.getAbsolutePath());
                logger.info("Save newFileName=="+newSize+"  信息=="+saveFile.getAbsolutePath());

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //// TODO: 返回保存后的文件信息 特别是文件大小与版本信息要准确
        //更新保存地址

        String oldFileUrl=wFileT.getFileUrl();
        long   oldSize=wFileT.getSize();


        FileModel filemodel = new FileModel();
        WFileVersionT fileVersion = new WFileVersionT();
        BeanUtils.copyProperties(wFileT, fileVersion);//复制现在版本



        filemodel.name = wFileT.getFileUrl();
        filemodel.size = newSize;
        filemodel.version = wFileT.getVersion() + 1;
        wFileT.setVersion( filemodel.version);
        wFileT.setSize(newSize);
//        wFileT.setFileUuid(uuid);
        wFileT.setFileUrl(fileUrl);//fileUrl 修改
        logger.info("oldFileUrl=="+oldFileUrl+"---newfileUrl=="+fileUrl);
        wFileT.setModifier(userid);

        iwFileTService.updateWFileT(wFileT);

        System.out.println("查看记录id是否变化----------原先=="+fileid+"-----现在=="+wFileT.getId());
        logger.info("查看记录idIsChange----------原先=="+fileid+"-----现在=="+wFileT.getId());

        // 保存历史版本

        //查询 获得上次的记录比较 是否是本人如果不是就添加 是的话就新增
        WFileVersionT findVersion=new WFileVersionT();
        findVersion.setFileId(fileid);
        List<WFileVersionT>  versionList=iwFileVersionTService.selectWFileVersionTList(findVersion);
        if (versionList!=null&&versionList.size()!=0){
            WFileVersionT maxNewVersion=versionList.get(0);
            //判断当前 修改者和最新修改记录的修改者是同一人
            if (maxNewVersion.getModifier().equals(userid)){
                //是的话 修改当前记录
                maxNewVersion.setVersion(wFileT.getVersion() - 1);
                maxNewVersion.setFileUrl(oldFileUrl);

                maxNewVersion.setSize(oldSize);
                maxNewVersion.setModifier(userid);
                maxNewVersion.setModifyTime(wFileT.getModifyTime());
//                maxNewVersion.setCreator(userid);


                iwFileVersionTService.updateWFileVersionT(maxNewVersion);

            }else{
                //不是就 添加记录
                if (oldSize>0){
                    fileVersion.setFileId(fileid);
                    fileVersion.setVersion(wFileT.getVersion() - 1);
//        fileVersion.setDownloadUrl(oldDownLoadUrl);
                    fileVersion.setFileUrl(oldFileUrl);

                    fileVersion.setSize(oldSize);
                    fileVersion.setModifier(userid);
                    fileVersion.setModifyTime(wFileT.getModifyTime());
//                    fileVersion.setCreator(userid);



                    iwFileVersionTService.insertWFileVersionT(fileVersion);
                }
            }
        }else{
            //直接添加
            if (oldSize>0){
                fileVersion.setFileId(fileid);
                fileVersion.setVersion(wFileT.getVersion() - 1);
//        fileVersion.setDownloadUrl(oldDownLoadUrl);
                fileVersion.setFileUrl(oldFileUrl);

                fileVersion.setSize(oldSize);
                fileVersion.setModifier(userid);
                fileVersion.setModifyTime(wFileT.getModifyTime());


                iwFileVersionTService.insertWFileVersionT(fileVersion);
            }
        }




        Map<String, Object> map = new HashMap<>();
        map.put("file", filemodel);

        return map;
    }

    @GetMapping("/weboffice/getFile")
    public ResponseEntity<byte[]> getFile(@RequestParam("_w_fileid") String fileid) throws Exception {
        //// TODO: 处理文件下载，返回对应的文件，如果是接第三方存储，可以没有这个接口
        System.out.println("进入====/weboffice/getFile");
        logger.info("进入====/weboffice/getFile");

//        WFileT wFile=iwFileTService.selectWFileTById(fileid);

//        File file = new File(wordBaseDirtory+"/"+wFile.getFileUrl());

        WFileT wFileT=iwFileTService.selectWFileTById(Long.parseLong(fileid));

        File file = new File(wordBaseDirtory+"/"+wFileT.getFileUrl());

        System.out.println("fileid="+fileid);
        logger.info("fileid="+fileid);
//        System.out.println("fileNameMap.get(fileid))="+fileNameMap.get(fileid));
        System.out.println("File"+file.getAbsolutePath());


        InputStream inputStream = new FileInputStream(file);
        byte[] body = new byte[inputStream.available()];
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+ URLEncoder.encode(wFileT.getName()+".docx", "utf-8"));
        inputStream.read(body);
        return new ResponseEntity(body, headers, HttpStatus.OK);
    }

    @GetMapping("/weboffice/getHistoryFile")
    public ResponseEntity<byte[]> getHistoryFile(@RequestParam("_w_hisfileid") String _w_hisfileid) throws Exception {
        //// TODO: 处理文件下载，返回对应的文件，如果是接第三方存储，可以没有这个接口
        System.out.println("进入====/weboffice/getHistoryFile");

//        WFileT wFile=iwFileTService.selectWFileTById(fileid);

//        File file = new File(wordBaseDirtory+"/"+wFile.getFileUrl());

        WFileVersionT fileVersion=iwFileVersionTService.selectWFileVersionTById(Long.parseLong(_w_hisfileid));
//        WFileT wFileT=iwFileTService.selectWFileTById(Long.parseLong(fileid));

        File file = new File(wordBaseDirtory+"/"+fileVersion.getFileUrl());

        System.out.println("_w_hisfileid="+_w_hisfileid);

//        System.out.println("fileNameMap.get(fileid))="+fileNameMap.get(fileid));
        System.out.println("File"+file.getAbsolutePath());


        InputStream inputStream = new FileInputStream(file);
        byte[] body = new byte[inputStream.available()];
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileVersion.getName()+".docx", "utf-8"));
        inputStream.read(body);
        return new ResponseEntity(body, headers, HttpStatus.OK);
    }

    /**
     * 获取所有历史版本文件信息
     */
    @RequestMapping("/v1/3rd/file/history")
    @ResponseBody
    public Object fileHistory(@RequestParam("_w_fileid") String fileid, HttpServletRequest request, HttpServletResponse response) {
//       System.out.println("获取所有历史版本文件信息param:{}"+JSON.toJSON(req));
         //通过fileId 查找相应 历史记录
        System.out.println("获取所有历史版本文件信息");
                Enumeration reqs=request.getParameterNames();
        while(reqs.hasMoreElements()) {
            String a=(String) reqs.nextElement();
            System.out.println("request参数名="+a+"参数值="+request.getParameter(a));

        }
        //返回数据
        List<FileHisDTO> result = new ArrayList<>(1);


        WFileVersionT fileVersion = new WFileVersionT();
        fileVersion.setFileId(fileid);
        List<WFileVersionT> versionTList = iwFileVersionTService.selectWFileVersionTList(fileVersion);
        if (versionTList != null && versionTList.size() > 0) {
            Set<String> userIdSet = new HashSet<>();

            for (WFileVersionT version:versionTList) {
                    userIdSet.add(version.getModifier());
                    userIdSet.add(version.getCreator());
            }

            List<String> userIdList = new ArrayList<>(userIdSet);
            String [] userIdS= userIdList.toArray(new String[userIdList.size()]);
            // 获取所有关联的人
            List<SysUser> userList = userService.selectRecordByIds(userIdS);

            if (userList != null && userList.size() > 0) {
                for (WFileVersionT version:versionTList) {
                    FileHisDTO fileHis = new FileHisDTO();
                    BeanUtils.copyProperties(version, fileHis);//复制相应信息


                    fileHis.setId(version.getFileId());
                    fileHis.setVersion(version.getVersion());
                    fileHis.setSize(version.getSize());
                    fileHis.setCreate_time(version.getCreateTime());
                    fileHis.setModify_time(version.getModifyTime());

                    fileHis.setDownload_url(download_host + "/weboffice/getHistoryFile?_w_hisfileid="+version.getId());
                    UserDTO creator = new UserDTO();
                    UserDTO modifier = new UserDTO();
                    for (SysUser user : userList) {
                        if (String.valueOf(user.getUserId()).equals(version.getCreator())) {
                            creator.setAvatar_url(GetAvatarSet(user.getUserId()));
                            creator.setId(String.valueOf(user.getUserId()));
                            creator.setName(user.getUserName());
                        }
                        if (String.valueOf(user.getUserId()).equals(version.getModifier())) {
                            modifier.setAvatar_url(GetAvatarSet(user.getUserId()));
                            modifier.setId(String.valueOf(user.getUserId()));
                            modifier.setName(user.getUserName());
                        }
                    }
                    fileHis.setModifier(modifier);
                    fileHis.setCreator(creator);
                    result.add(fileHis);
                }
            }

        }

        System.out.println(Response.success(result));
        Map<String, Object> map = new HashMap<>();
        map.put("histories", result);


//        return Response.success(map);
        return map;
    }



    @GetMapping("/v1/file/{fileid}")
    @ResponseBody
    public Object  getFileUrl(@PathVariable("fileid") Long fileid) throws Exception {
        //// TODO: 处理文件下载，返回对应的文件，如果是接第三方存储，可以没有这个接口
        System.out.println("进入====v1/file/{fileid}");
        String fileUrl="";
        if (fileid!=null){
            fileUrl=intrServerIp+"/weboffice/getFile?_w_fileid="+fileid;

        }
        Map<String, Object> map = new HashMap<>();
        map.put("url", fileUrl);
        return  map;
    }







     public  String AvatarSet(String  avatar){

        if (StringUtils.isNotEmpty(avatar)){
            return  intrServerIp+avatar;
        }else{
            return  null;
        }
     }

    public  String GetAvatarSet(Long  userId){

        if (StringUtils.isNotEmpty(String.valueOf(userId))){
            return  intrServerIp+"/system/user/getAvatar/"+userId;
//            return  "/system/user/getAvatar/"+userId;

        }else{
            return  null;
        }
    }
}
